/**
 * 
 */
package demo.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Calendar;

import javax.mail.MessagingException;
import javax.mail.Session;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import demo.mail.MailService;
import demo.servlet.util.ContentType;

/**
 * @author roger.xu
 * 
 */
public class MailServlet extends HttpServlet {

    private static final long serialVersionUID = -4795934565080815117L;

    private static final Log _log = LogFactory.getLog(MailServlet.class.getSimpleName());

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String message = "Ready to send JavaMail";

        if (StringUtils.equals(req.getParameter("send"), String.valueOf(1))) {
            try {
                final Context initCtx = new InitialContext();
                final Context envCtx = (Context) initCtx.lookup("java:comp/env");
                final Session session = (Session) envCtx.lookup("mail/Session");

                final String from = null;
                final String to = "roger.xu.2007@gmail.com";
                final String cc = null;
                final String subject = "JNDI JavaMail Test";
                final String content = "Send from JNDI JavaMail";

                MailService.sendAsPlainText(session, from, to, cc, subject, content);
                message = String.format("JavaMail has been sent to %s", to);

            } catch (NamingException e) {
                message = e.getMessage();
                _log.error(e.getMessage(), e);
            } catch (MessagingException e) {
                message = e.getMessage();
                _log.error(e.getMessage(), e);
            } catch (IOException e) {
                message = e.getMessage();
                _log.error(e.getMessage(), e);
            }
        }

        resp.setContentType(ContentType.HTML);
        final PrintWriter out = resp.getWriter();
        out.println(message);
        out.println("<br />");
        out.println(Calendar.getInstance().getTime().toString());
        out.flush();
        return;
    }
}
